<template>
  <div class="resource-management">
    <h1 class="page-title">
      <el-icon><FolderOpened /></el-icon>
      资源管理
    </h1>

    <!-- 操作工具栏 -->
    <el-card class="toolbar-card mb-20">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="8">
          <el-input
            v-model="searchQuery"
            placeholder="搜索资源标题或描述..."
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :xs="24" :sm="6">
          <el-select v-model="categoryFilter" placeholder="选择分类" clearable @change="loadResources">
            <el-option
              v-for="category in categories"
              :key="category.value"
              :label="category.label"
              :value="category.value"
            />
          </el-select>
        </el-col>
        <el-col :xs="24" :sm="6">
          <el-select v-model="difficultyFilter" placeholder="选择难度" clearable @change="loadResources">
            <el-option label="入门" value="beginner" />
            <el-option label="初级" value="basic" />
            <el-option label="中级" value="intermediate" />
            <el-option label="高级" value="advanced" />
          </el-select>
        </el-col>
        <el-col :xs="24" :sm="4">
          <el-button type="primary" @click="showCreateDialog = true">
            <el-icon><Plus /></el-icon>
            新增资源
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 资源列表 -->
    <el-card class="resource-list-card">
      <template #header>
        <div class="list-header">
          <span>资源列表 (共 {{ pagination.total }} 个)</span>
          <el-button-group>
            <el-button :type="viewMode === 'table' ? 'primary' : 'default'" @click="viewMode = 'table'">
              <el-icon><List /></el-icon>
              表格视图
            </el-button>
            <el-button :type="viewMode === 'card' ? 'primary' : 'default'" @click="viewMode = 'card'">
              <el-icon><Grid /></el-icon>
              卡片视图
            </el-button>
          </el-button-group>
        </div>
      </template>

      <!-- 表格视图 -->
      <el-table
        v-if="viewMode === 'table'"
        v-loading="loading"
        :data="resources"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="标题" min-width="200" />
        <el-table-column prop="category" label="分类" width="120" align="center">
          <template #default="{ row }">
            <el-tag :type="getCategoryType(row.category)" size="small">
              {{ getCategoryLabel(row.category) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="difficulty" label="难度" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getDifficultyType(row.difficulty)" size="small">
              {{ getDifficultyLabel(row.difficulty) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="创建者" width="120">
          <template #default="{ row }">
            {{ row.creator?.real_name || row.creator?.username || '系统' }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button size="small" @click="previewResource(row)">
                <el-icon><View /></el-icon>
              </el-button>
              <el-button size="small" type="primary" @click="editResource(row)">
                <el-icon><Edit /></el-icon>
              </el-button>
              <el-button size="small" type="danger" @click="deleteResource(row)">
                <el-icon><Delete /></el-icon>
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 卡片视图 -->
      <div v-else class="resources-grid">
        <div
          v-for="resource in resources"
          :key="resource.id"
          class="resource-card-item"
        >
          <el-card class="resource-card" :body-style="{ padding: '0px' }">
            <div class="card-image">
              <img v-if="resource.image" :src="resource.image" :alt="resource.title" />
              <div v-else class="image-placeholder">
                <el-icon class="placeholder-icon"><component :is="getCategoryIcon(resource.category)" /></el-icon>
              </div>
              <div class="card-overlay">
                <el-button-group>
                  <el-button size="small" @click="previewResource(resource)">
                    <el-icon><View /></el-icon>
                  </el-button>
                  <el-button size="small" type="primary" @click="editResource(resource)">
                    <el-icon><Edit /></el-icon>
                  </el-button>
                  <el-button size="small" type="danger" @click="deleteResource(resource)">
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </el-button-group>
              </div>
            </div>
            <div class="card-content">
              <h3 class="card-title">{{ resource.title }}</h3>
              <p class="card-description">{{ resource.description }}</p>
              <div class="card-footer">
                <div class="card-tags">
                  <el-tag :type="getCategoryType(resource.category)" size="small">
                    {{ getCategoryLabel(resource.category) }}
                  </el-tag>
                  <el-tag :type="getDifficultyType(resource.difficulty)" size="small">
                    {{ getDifficultyLabel(resource.difficulty) }}
                  </el-tag>
                </div>
                <span class="card-creator">{{ resource.creator?.username || '系统' }}</span>
              </div>
            </div>
          </el-card>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[12, 24, 48, 96]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadResources"
          @current-change="loadResources"
        />
      </div>
    </el-card>

    <!-- 创建/编辑资源弹窗 -->
    <el-dialog
      v-model="showCreateDialog"
      :title="editingResource ? '编辑资源' : '新增资源'"
      width="800px"
    >
      <el-form
        ref="resourceFormRef"
        :model="resourceForm"
        :rules="resourceRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="资源标题" prop="title">
              <el-input v-model="resourceForm.title" placeholder="请输入资源标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资源链接" prop="url">
              <el-input v-model="resourceForm.url" placeholder="请输入资源链接" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="资源分类" prop="category">
              <el-select v-model="resourceForm.category" placeholder="选择分类" style="width: 100%">
                <el-option
                  v-for="category in categories"
                  :key="category.value"
                  :label="category.label"
                  :value="category.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="难度等级" prop="difficulty">
              <el-select v-model="resourceForm.difficulty" placeholder="选择难度" style="width: 100%">
                <el-option label="入门" value="beginner" />
                <el-option label="初级" value="basic" />
                <el-option label="中级" value="intermediate" />
                <el-option label="高级" value="advanced" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="资源描述" prop="description">
          <el-input
            v-model="resourceForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入资源描述"
          />
        </el-form-item>

        <el-form-item label="封面图片" prop="image">
          <el-input v-model="resourceForm.image" placeholder="请输入图片链接（可选）" />
        </el-form-item>

        <el-form-item label="详细内容">
          <el-input
            v-model="resourceForm.content"
            type="textarea"
            :rows="6"
            placeholder="请输入详细内容（支持HTML，可选）"
          />
        </el-form-item>

        <el-form-item label="关键特点">
          <el-input
            v-model="featuresText"
            type="textarea"
            :rows="3"
            placeholder="请输入关键特点，每行一个"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelEdit">取消</el-button>
          <el-button type="primary" @click="saveResource" :loading="saving">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 资源预览弹窗 -->
    <el-dialog
      v-model="showPreviewDialog"
      :title="previewResourceData?.title"
      width="900px"
      class="preview-dialog"
    >
      <div v-if="previewResourceData" class="resource-preview">
        <div class="preview-header">
          <div class="preview-image">
            <img v-if="previewResourceData.image" :src="previewResourceData.image" :alt="previewResourceData.title" />
            <div v-else class="preview-placeholder">
              <el-icon class="placeholder-icon"><component :is="getCategoryIcon(previewResourceData.category)" /></el-icon>
            </div>
          </div>
          <div class="preview-info">
            <h2>{{ previewResourceData.title }}</h2>
            <p>{{ previewResourceData.description }}</p>
            <div class="preview-meta">
              <el-tag :type="getCategoryType(previewResourceData.category)">
                {{ getCategoryLabel(previewResourceData.category) }}
              </el-tag>
              <el-tag :type="getDifficultyType(previewResourceData.difficulty)">
                {{ getDifficultyLabel(previewResourceData.difficulty) }}
              </el-tag>
            </div>
          </div>
        </div>

        <div class="preview-content" v-if="previewResourceData.content">
          <h3>详细内容</h3>
          <div v-html="previewResourceData.content"></div>
        </div>

        <div class="preview-features" v-if="previewResourceData.features?.length">
          <h3>主要特点</h3>
          <ul>
            <li v-for="feature in previewResourceData.features" :key="feature">{{ feature }}</li>
          </ul>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showPreviewDialog = false">关闭</el-button>
          <el-button type="primary" @click="openResourceLink(previewResourceData?.url)">
            <el-icon><Link /></el-icon>
            访问资源
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '@/utils/api'

// 状态数据
const loading = ref(false)
const saving = ref(false)
const resources = ref([])
const searchQuery = ref('')
const categoryFilter = ref('')
const difficultyFilter = ref('')
const viewMode = ref('table')
const showCreateDialog = ref(false)
const showPreviewDialog = ref(false)
const editingResource = ref(null)
const previewResourceData = ref(null)

// 分页数据
const pagination = ref({
  page: 1,
  pageSize: 12,
  total: 0
})

// 资源分类
const categories = ref([
  { label: 'HTML/CSS', value: 'html-css', icon: 'Document' },
  { label: 'JavaScript', value: 'javascript', icon: 'Lightning' },
  { label: 'C#', value: 'csharp', icon: 'Cpu' },
  { label: 'Vue.js', value: 'vue', icon: 'Grid' },
  { label: '工具软件', value: 'tools', icon: 'Tools' },
  { label: '视频教程', value: 'videos', icon: 'VideoPlay' },
  { label: '电子书籍', value: 'books', icon: 'Reading' },
  { label: '在线课程', value: 'courses', icon: 'School' }
])

// 资源表单
const resourceForm = ref({
  title: '',
  description: '',
  url: '',
  category: '',
  difficulty: 'basic',
  image: '',
  content: '',
  features: []
})

const featuresText = ref('')
const resourceFormRef = ref()

const resourceRules = {
  title: [
    { required: true, message: '请输入资源标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度应在 2 到 100 个字符', trigger: 'blur' }
  ],
  url: [
    { required: true, message: '请输入资源链接', trigger: 'blur' },
    { type: 'url', message: '请输入正确的URL格式', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择资源分类', trigger: 'change' }
  ],
  difficulty: [
    { required: true, message: '请选择难度等级', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入资源描述', trigger: 'blur' },
    { min: 10, max: 500, message: '描述长度应在 10 到 500 个字符', trigger: 'blur' }
  ]
}

// 加载资源列表
const loadResources = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.value.page,
      pageSize: pagination.value.pageSize,
      search: searchQuery.value,
      category: categoryFilter.value,
      difficulty: difficultyFilter.value
    }

    const response = await api.get('/admin/resources', { params })
    if (response.data.success) {
      resources.value = response.data.data.resources
      pagination.value.total = response.data.data.total
    }
  } catch (error) {
    console.error('加载资源列表失败:', error)
    ElMessage.error('加载资源列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  pagination.value.page = 1
  loadResources()
}

// 编辑资源
const editResource = (resource) => {
  editingResource.value = resource
  resourceForm.value = {
    title: resource.title,
    description: resource.description,
    url: resource.url,
    category: resource.category,
    difficulty: resource.difficulty,
    image: resource.image || '',
    content: resource.content || '',
    features: resource.features || []
  }
  featuresText.value = (resource.features || []).join('\n')
  showCreateDialog.value = true
}

// 预览资源
const previewResource = (resource) => {
  previewResourceData.value = resource
  showPreviewDialog.value = true
}

// 保存资源
const saveResource = async () => {
  if (!resourceFormRef.value) return

  try {
    await resourceFormRef.value.validate()
    saving.value = true

    // 处理特点列表
    const features = featuresText.value
      .split('\n')
      .map(f => f.trim())
      .filter(f => f.length > 0)

    const formData = {
      ...resourceForm.value,
      features
    }

    let response
    if (editingResource.value) {
      response = await api.put(`/admin/resources/${editingResource.value.id}`, formData)
    } else {
      response = await api.post('/admin/resources', formData)
    }

    if (response.data.success) {
      ElMessage.success(editingResource.value ? '资源更新成功' : '资源创建成功')
      cancelEdit()
      loadResources()
    }
  } catch (error) {
    if (error.name === 'ValidationError') return
    console.error('保存资源失败:', error)
    ElMessage.error('保存资源失败')
  } finally {
    saving.value = false
  }
}

// 删除资源
const deleteResource = async (resource) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除资源「${resource.title}」吗？此操作不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'error'
      }
    )

    const response = await api.delete(`/admin/resources/${resource.id}`)
    if (response.data.success) {
      ElMessage.success('资源删除成功')
      loadResources()
    }
  } catch (error) {
    if (error === 'cancel') return
    console.error('删除资源失败:', error)
    ElMessage.error('删除资源失败')
  }
}

// 取消编辑
const cancelEdit = () => {
  showCreateDialog.value = false
  editingResource.value = null
  resourceForm.value = {
    title: '',
    description: '',
    url: '',
    category: '',
    difficulty: 'basic',
    image: '',
    content: '',
    features: []
  }
  featuresText.value = ''
}

// 打开资源链接
const openResourceLink = (url) => {
  if (url) {
    window.open(url, '_blank')
  }
}

// 工具函数
const getCategoryIcon = (category) => {
  const categoryData = categories.value.find(cat => cat.value === category)
  return categoryData?.icon || 'Document'
}

const getCategoryLabel = (category) => {
  const categoryData = categories.value.find(cat => cat.value === category)
  return categoryData?.label || '其他'
}

const getCategoryType = (category) => {
  const typeMap = {
    'html-css': 'primary',
    'javascript': 'warning',
    'csharp': 'success',
    'vue': 'info',
    'tools': 'danger',
    'videos': 'primary',
    'books': 'warning',
    'courses': 'success'
  }
  return typeMap[category] || 'default'
}

const getDifficultyLabel = (difficulty) => {
  const labelMap = {
    'beginner': '入门',
    'basic': '初级',
    'intermediate': '中级',
    'advanced': '高级'
  }
  return labelMap[difficulty] || difficulty
}

const getDifficultyType = (difficulty) => {
  const typeMap = {
    'beginner': 'success',
    'basic': 'primary',
    'intermediate': 'warning',
    'advanced': 'danger'
  }
  return typeMap[difficulty] || 'default'
}

const formatDate = (date) => {
  return new Date(date).toLocaleString('zh-CN')
}

// 组件挂载
onMounted(() => {
  loadResources()
})
</script>

<style scoped>
.resource-management {
  padding: 0;
}

/* 通用样式 */
.mb-20 {
  margin-bottom: 20px;
}

.page-title {
  display: flex;
  align-items: center;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 24px;
}

.page-title .el-icon {
  margin-right: 12px;
  color: #409eff;
  font-size: 28px;
}

/* 工具栏 */
.toolbar-card {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border-radius: 12px;
}

/* 资源列表 */
.resource-list-card {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border-radius: 12px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 500;
}

/* 卡片视图 */
.resources-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.resource-card-item {
  height: 100%;
}

.resource-card {
  height: 100%;
  overflow: hidden;
  transition: all 0.3s;
  border-radius: 12px;
}

.resource-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 30px rgba(0, 0, 0, 0.15);
}

.card-image {
  position: relative;
  height: 160px;
  overflow: hidden;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.card-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: white;
}

.placeholder-icon {
  font-size: 48px;
  opacity: 0.8;
}

.card-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.resource-card:hover .card-overlay {
  opacity: 1;
}

.card-content {
  padding: 16px;
}

.card-title {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.card-description {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #606266;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-tags {
  display: flex;
  gap: 4px;
}

.card-creator {
  font-size: 12px;
  color: #909399;
}

/* 分页 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 预览弹窗 */
.preview-header {
  display: flex;
  gap: 20px;
  margin-bottom: 24px;
}

.preview-image {
  flex-shrink: 0;
  width: 120px;
  height: 120px;
  border-radius: 8px;
  overflow: hidden;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.preview-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.preview-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: white;
}

.preview-info {
  flex: 1;
}

.preview-info h2 {
  margin: 0 0 12px 0;
  color: #303133;
}

.preview-info p {
  margin: 0 0 16px 0;
  color: #606266;
  line-height: 1.6;
}

.preview-meta {
  display: flex;
  gap: 8px;
}

.preview-content,
.preview-features {
  margin-top: 24px;
}

.preview-content h3,
.preview-features h3 {
  margin: 0 0 12px 0;
  color: #303133;
}

.preview-features ul {
  margin: 0;
  padding-left: 20px;
}

.preview-features li {
  margin-bottom: 8px;
  color: #606266;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-title {
    font-size: 20px;
  }
  
  .resources-grid {
    grid-template-columns: 1fr;
  }
  
  .preview-header {
    flex-direction: column;
  }
  
  .preview-image {
    width: 100%;
    height: 200px;
  }
}
</style> 